<template>
  <div>
    <div class="short-back" @click="shortBack">
      <a-icon type="arrow-left" :style="{ fontSize: '18px', color: '#008FFF' }" />
      <span class="back-tip">返回</span>
    </div>
    <div class="msgTip">
      您的手机号<span class="blue">{{ tipMobile }} </span>已收到短信验证码,请注意查收!
    </div>
    <a-form class="short-form" :form="form">
      <a-form-item>
        <a-row :gutter="24">
          <a-col :span="24" style="position:relative">
            <a-input
              class="msg-input"
              size="large"
              placeholder=""
              :maxLength="4"
              @keydown.enter.native="handleSubmit"
              autocomplete="off"
              v-decorator="['code', { rules: [{ required: true, validator: validateCode }] }]"
            >
            </a-input>
            <div class="msgBtn">
              <a-button type="primary" @click="getCode" :loading="timeGo" style="width: 100%">
                <span v-show="!timeGo">获取验证码</span>
                <span v-show="timeGo">&nbsp;{{ time }}&nbsp;秒</span>
              </a-button>
            </div>
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item style="margin-top: 78px">
        <a-button size="large" type="primary" :loading="loginBtn" class="login-btn" @click="handleSubmit">
          <span style="font-size: 14px">确认</span>
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { getShortCode, validShortCode } from '@/api/user'
import { validatePhone, validateCode, validatePassword } from '@/utils/validate'
import { USERISFIRSTLOGIN } from '@/store/mutation-types'
export default {
  name: 'ShortForm',
  data () {
    return {
      timeGo: false,
      time: 90,
      loginBtn: false,
      model: {}
    }
  },
  props: {
    loginInfo: {
      type: Object,
      required: false,
      default: () => {}
    }
  },
  computed: {
    tipMobile () {
      let reg = new RegExp('(\\d{3})(\\d{4})(\\d{4})')
      return this.loginInfo.mobile.replace(reg, '$1****$3')
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },

  destroyed () {
    clearInterval(this.timer)
  },

  methods: {
    shortBack () {
      this.$emit('stepChange', -3)
    },
    // 获取短信验证码
    getCode () {
      this.timeGo = true
      this.timer = setInterval(() => {
        this.time -= 1
        if (this.time === 0) {
          clearInterval(this.timer)
          this.time = 90
          this.timeGo = false
        }
      }, 1000)
      const params = {
        userName: this.loginInfo.username,
        mobile: this.loginInfo.mobile
      }
      // 发送短信验证码
      getShortCode(params)
        .then(res => {
          if (res.code === 0 && res.data) {
            this.$message.success(res.msg)
          } else {
            this.$message.error(res.msg)
            clearInterval(this.timer)
            this.timeGo = false
            this.time = 90
          }
        })
        .catch(() => {
          clearInterval(this.timer)
          this.timeGo = false
          this.time = 90
        })
    },

    // 提交登录
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          const { username, mobile } = this.loginInfo
          if (this.isLocking(username)) {
            // 用户已被锁定
            return
          }
          this.loginBtn = true
          const params = {
            userName: username,
            mobile,
            code: values.code
          }
          // 验证短信验证码
          validShortCode(params)
            .then(res => {
              if (res.code === 0 && res.data) {
                this.model = Object.assign({}, values)
                let isFirstLogin = localStorage.getItem('Main__' + USERISFIRSTLOGIN)
                if (isFirstLogin === null) {
                  this.$emit('ok', true)
                } else {
                  this.loginBtn = true
                  this.login(this.loginInfo)
                }
              } else {
                this.$message.error(res.msg)
                this.loginBtn = false
                this.lockingUser(username)
                this.form.setFieldsValue({ code: '' })
              }
            })
            .catch(() => (this.loginBtn = false))
        }
      })
    },
    loginFun () {
      this.loginBtn = true
      this.login(this.loginInfo)
    },
    // 用户登录
    login (data) {
      this.$store
        .dispatch('mobileLogin', data)
        .then(() => {
          this.$notification.success({
            message: '系统提示',
            description: '登录成功',
            duration: 3,
            top: '62px'
          })
          this.unLockingUser(data.username)
          this.$router.push({ path: '/' })
        })
        .catch(() => {
          this.loginBtn = false
          this.lockingUser(data.username)
          this.form.setFieldsValue({ code: '' })
        })
    },

    // 验证用户是否被锁定
    isLocking (name) {
      const locking = this.$ls.get('User_Locking')
      if (locking[name] && locking[name]['num'] >= 5) {
        if (locking[name].expire - Date.now() > 0) {
          // 处于锁定时间中
          this.$message.error(
            `用户已经被锁定，请于${Math.ceil((locking[name].expire - Date.now()) / (60 * 1000))}分钟之后再试`
          )
          return true
        } else {
          this.unLockingUser(name)
          return false
        }
      } else {
        return false
      }
    },

    // 锁定用户
    lockingUser (name) {
      const locking = this.$ls.get('User_Locking')

      let userLocking = locking[name]

      if (userLocking) {
        if (userLocking.num === 4) {
          userLocking.num += 1
          userLocking.expire = Date.now() + 10 * 60 * 1000 // 锁定时间为10分钟
        } else {
          userLocking.num += 1
        }
      } else {
        locking[name] = { num: 1 }
      }

      this.$ls.set('User_Locking', locking)
    },

    // 解锁用户
    unLockingUser (name) {
      const locking = this.$ls.get('User_Locking')
      if (locking[name]) {
        delete locking[name]
      }
      this.$ls.set('User_Locking', locking)
    },

    validatePassword,
    validateCode,
    validatePhone
  }
}
</script>

<style lang="less" scoped>
.short-back {
  position: absolute;
  top: 10px;
  left: 20px;
  height: 20px;
  line-height: 20px;
  cursor: pointer;
  .back-tip {
    color: #333333;
    font-weight: 500;
    margin-left: 4px;
  }
}
.msgTip {
  color: #656565;
  padding: 0 25px;
  text-align: center;
}
.short-form {
  padding: 70px 42px 0 50px;
}
.msg-input {
  letter-spacing: 10px;
  font-size: 18px;
  text-indent: 56px;
  color: #333333;
  font-weight: bold;
  font-size: 30px !important;
}
.login-btn {
  width: 100%;
}

.msgBtn {
  position: absolute;
  right: 16px;
  top: -6px;
}
::placeholder {
  font-size: 18px !important;
  font-weight: 400;
  text-indent: 60px;
}
</style>
